using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.User;
using B.S.NewMedical.Domain.User;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.NewMedical.Api.Write.Application.Handler.User
{
    /// <summary>
    /// 保存用户权限处理器
    /// </summary>
    public class SaveUserPermissionsHandler : IRequestHandler<SaveUserPermissionsCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<UserPermissionModel> _userPermissionRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<SaveUserPermissionsHandler> _logger;

        public SaveUserPermissionsHandler(
            IBaseRepository<UserPermissionModel> userPermissionRepository,
            IBaseRepository<UserModel> userRepository,
            IMapper mapper,
            ILogger<SaveUserPermissionsHandler> logger)
        {
            _userPermissionRepository = userPermissionRepository;
            _userRepository = userRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(SaveUserPermissionsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证用户是否存在
                var user = await _userRepository.GetValue(request.UserId);
                if (user == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "用户不存在"
                    };
                }

                // 删除用户现有权限
                var existingPermissions = _userPermissionRepository.GetAll()
                    .Where(up => up.UserId == request.UserId && !up.IsDeleted)
                    .ToList();

                foreach (var permission in existingPermissions)
                {
                    permission.IsDeleted = true;
                    permission.UpdateTime = DateTime.Now;
                    permission.UpdatePeople = "System"; // 实际项目中应该从当前用户获取
                    await _userPermissionRepository.UpdateAsync(permission);
                }

                // 添加新权限
                var newPermissions = new List<UserPermissionModel>();
                foreach (var permissionId in request.PermissionIds)
                {
                    var userPermission = new UserPermissionModel
                    {
                        UserId = request.UserId,
                        PermissionId = permissionId,
                        IsEnabled = true,
                        CreateTime = DateTime.Now,
                        CreatePeople = "System" // 实际项目中应该从当前用户获取
                    };
                    newPermissions.Add(userPermission);
                }

                // 批量保存新权限
                foreach (var permission in newPermissions)
                {
                    await _userPermissionRepository.CreateAsync(permission);
                }

                _logger.LogInformation("成功保存用户权限，用户ID：{UserId}，权限数量：{PermissionCount}", 
                    request.UserId, request.PermissionIds.Count);

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "保存用户权限成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存用户权限时发生异常");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = "保存用户权限失败：" + ex.Message
                };
            }
        }
    }
} 